package server;

import java.awt.Color;
import java.net.MalformedURLException;
import java.rmi.Naming;
import java.rmi.Remote;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;

import client.ClientUpdateImpl;

import network.ClientUpdates;

import common.Level;
import common.Player;

public class Foop1GameServer {

	private Level level;
	private Player[] player = new Player[3];
	private ClientUpdates[] client = new ClientUpdates[3]; 
	
	Foop1GameServer( Level level) {
		this.level = level;
		this.player[Player.PLAYER1] = new Player( 0,0, Color.GRAY);
		this.player[Player.PLAYER2] = new Player( level.getColumnAmount()-1, 0, Color.GRAY);
		this.player[Player.PLAYER3] = new Player( 0, level.getRowAmount()-1, Color.GRAY);
		initialize();
	}
	
	public void run(){
		System.out.println( "Server running... waiting for Players...");
		/*
		 * main loop goes here
		 */
	}
	
	public void initialize(){
		try {
			LocateRegistry.createRegistry(Registry.REGISTRY_PORT);
			System.out.println("Server : Registry wurde erzeugt.");
			Naming.rebind("ServerUpdate", new ServerUpdateImpl(this));
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (MalformedURLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/*
	 * assign client to player
	 */
	public boolean registerClient( ClientUpdates cU){
		for( int i = 0; i < 3; i++){
			if( client[i] == null){
				client[i] = cU;
				player[i].setColor( Player.PLAYERCOLOR[i]);
				System.out.println( "Client connected: Assigned Player " + i + " (" + Player.PLAYERCOLOR[i].toString() + ")");
				try {
					cU.showText( "You are player " + i);
				} catch (RemoteException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				return true;
			}
		}
		return false;
	}
}
